package org.linlinjava.litemall.db.handler;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class ListMapTypeHandler extends BaseTypeHandler<List<Map<String, String>>> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<Map<String, String>> parameter, JdbcType jdbcType) throws SQLException {
        try {
            String jsonString = objectMapper.writeValueAsString(parameter);
            ps.setString(i, jsonString);
        } catch (JsonProcessingException e) {
            throw new SQLException("Error converting List<Map<Integer, String>> to JSON string", e);
        }
    }

    @Override
    public List<Map<String, String>> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String jsonString = rs.getString(columnName);
        return convertJsonToListMap(jsonString);
    }

    @Override
    public List<Map<String, String>> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String jsonString = rs.getString(columnIndex);
        return convertJsonToListMap(jsonString);
    }

    @Override
    public List<Map<String, String>> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String jsonString = cs.getString(columnIndex);
        return convertJsonToListMap(jsonString);
    }

    private List<Map<String, String>> convertJsonToListMap(String jsonString) throws SQLException {
        if (StrUtil.isEmpty(jsonString)) {
            return null;
        }
        try {
            return objectMapper.readValue(jsonString, new TypeReference<List<Map<String, String>>>() {});
        } catch (JsonProcessingException e) {
            throw new SQLException("Error converting JSON string to List<Map<Integer, String>>", e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}


